import helper from "@/helper/helper";
import store from "../index";
import router, { resetRouter } from "@/router";
import config from "@/helper/config";
import { authLogin, userLogout, getAuthToken, getInfo } from "@/api";
import { Modal } from "ant-design-vue";
// import { getAuthToken, userLogout } from '@/api'
const User = {
  namespaced: false,
  state: {
    userInfo: {},
    roles: [],
    refreshToken: "",
    screenType: false,
  },
  getters: {
    userInfo(state) {
      return state.userInfo;
    },
    roles(state) {
      return state.roles;
    },
    refreshToken(state) {
      return state.refreshToken;
    },
    screenType(state) {
      return state.screenType;
    },
  },
  mutations: {
    SET_USER_INFO(state, value) {
      state.userInfo = value;
    },
    SET_ROLES(state, value) {
      state.roles = value;
    },
    SET_REFRESH_TOKEN(state, value) {
      state.refreshToken = value;
    },
    screenType(state, value) {
      state.screenType = value;
    },
  },
  actions: {
    async login({ commit }, params) {
      // 调用接口
      const res = await authLogin(params);
      helper.setToken(res?.token);
      helper.pageHide();
      return res;
    },
    // 授权码获取token
    async getTokenByCode({ commit }, params) {
      const { data } = await getAuthToken(params);
      helper.setToken(data.access_token);
      commit("SET_REFRESH_TOKEN", data.refresh_token);
      helper.pageHide();
      return data;
    },
    // 业务系统----获取用户详细信息
    async getUserInfo({ commit }) {
      // const { user, permissions, roles } = await getInfo(config.clientId);
      const { user } = await getInfo();
      commit("SET_USER_INFO", user);
      return user;
    },
    logout({ dispatch }) {
      Modal.confirm({
        title: "提示",
        content: "确定退出登录吗?",
        async onOk() {
          try {
            const { code } = await userLogout();
            if (code === 200) {
              helper.msg.success("退出成功!");
            }
          } finally {
            dispatch("clearStore");
            // 统一认证逻辑直接放到子系统------
            // router.push({ name: 'login' })
            dispatch("tagsView/delAllViews");
            if (config.systemType === "business") {
              const redirectUri = encodeURIComponent(
                "http://" + window.location.host + "/"
              );
              window.location.href = `${config.ssoUrl}/login?client_id=${config.clientId}&redirect_uri=${redirectUri}`;
            } else {
              router.push({ name: "login" });
            }
            Modal.destroyAll();
          }
        },
        onCancel() {
          helper.msg.success("取消退出!");
        },
      });
    },
    clearStore({ commit }) {
      commit("SET_USER_INFO", {});
      commit("SET_ROLES", []);
      store.commit("SET_PERMISSION", []);
      store.commit("SET_RouteNames", []);
      resetRouter();
      helper.removeToken();
      helper.storage.clear();
    },
  },
};

export default User;
